extends Control

const api_origin = 'http://121.42.167.194/log'
#const api_origin = 'http://localhost:8900/log'

onready var name_list = get_node('vbox/name_list')
onready var action_menu = get_node('vbox/title_bar/btn_menu')
onready var title_label = get_node('vbox/title_bar/title')
onready var btn_edit = get_node('vbox/list_edit_bar/btn_edit')
onready var btn_delete = get_node('vbox/list_edit_bar/btn_delete')
onready var name_panel = get_node('name_panel')
onready var file_dialog = get_node('file_dialog')
onready var http_get = get_node('HTTP_get')
onready var http_post = get_node('HTTP_post')
onready var http_panel = get_node('HTTP_panel')
onready var date_panel = get_node('date_panel')
onready var comment_panel = get_node('comment_panel')
onready var helper = Helper.new()
onready var title_base = title_label.get_text()

var is_add_name = true
var date_time = OS.get_date()
var names = StringArray()
var tags_list = []

func _ready():
	update_title()
	fetch_data()
	action_menu.get_popup().connect('item_pressed', self, 'on_action_menu_item')
	set_process_unhandled_input(true)

func update_title():
	title_label.set_text(title_base + ' (' + helper.date_to_str(date_time) + ')')

func fetch_data():
	http_panel.show()
	var url = helper.get_url(date_time)
	http_get.request(url, [], false, HTTPClient.METHOD_GET, '')

func post_data():
	var tags = StringArray()
	for idx in range(names.size()):
		tags.push_back(join_tags(tags_list[idx], '|'))

	var body = {
		'names': names,
		'tags': tags,
		'cup_size': comment_panel.get_cup_size(),
		'comment': comment_panel.get_comment()
	}
	var url = helper.get_url(date_time)

	var header = StringArray(['Content-Type: application/json'])
	http_post.request(url, header, false, HTTPClient.METHOD_POST, body.to_json())

func _on_btn_add_pressed():
	is_add_name = true
	name_panel.show_name('', [])

func _on_btn_edit_pressed():
	if name_list.get_selected_items().size() == 0:
		return
	is_add_name = false
	var idx = name_list.get_selected_items()[0]
	name_panel.show_name(names[idx], tags_list[idx])

func _on_btn_delete_pressed():
	if name_list.get_selected_items().size() == 0:
		return
	var idx = name_list.get_selected_items()[0]
	name_list.remove_item(idx)
	names.remove(idx)
	tags_list.remove(idx)
	post_data()
	update_button_state(0)

func on_new_name(name, tags):
	if is_add_name:
		names.push_back(name)
		tags_list.push_back(tags)
	else:
		var idx = name_list.get_selected_items()[0]
		names[idx] = name
		tags_list[idx] = tags

	fill_name_list()
	post_data()
	update_button_state(0)


func on_file_dialog_confirmed():
	var filepath = file_dialog.get_current_path()
	var file = File.new()
	var size = names.size()
	file.open(filepath, File.WRITE)
	file.store_line('杯数' + str(comment_panel.get_cup_size()))
	file.store_line('人数' + str(size))
	for index in range(size):
		file.store_line(names[index])
	file.close()

func on_action_menu_item(index):
	if index == 0:
		file_dialog.popup_centered_ratio()
	elif index == 1:
		comment_panel.show()
	elif index == 2:
		post_data()
	elif index == 3:
		date_panel.show_date(date_time)


func on_get_request_completed( result, response_code, headers, body ):
	if result != HTTPRequest.RESULT_SUCCESS:
		http_panel.showErrorText('连接服务器时遇到错误 -\n'\
			+ helper.http_result_to_str(result) + '\n' + '错误代码：' + str(result))
		return
	var body_str = body.get_string_from_utf8()
	var json_body = {}
	json_body.parse_json(body_str)
	if response_code >= 400:
		http_panel.showErrorText('服务器运行时出错: ' + str(response_code) + '\n' + json_body.msg)
		return
	comment_panel.set_cup_size(json_body.cup_size)
	comment_panel.set_comment(json_body.comment)
	names = json_body.names
	tags_list = deserialize_tags(json_body.tags)
	fill_name_list()
	http_panel.hide()

func deserialize_tags(tags):
	var new_tags_arr = []
	for idx in range(tags.size()):
		new_tags_arr.push_back(str(tags[idx]).split('|'))
	return new_tags_arr

func join_tags(tag_arr, sep):
	if tag_arr.size() == 0:
		return ''
	var join_str = tag_arr[0]
	for idx in range(1, tag_arr.size()):
		join_str = join_str + sep + tag_arr[idx]
	return join_str

func get_tag_surfix(tags):
	var tag_str = join_tags(tags, ', ')
	if tag_str == '':
		return tag_str
	else:
		return '（' + tag_str + '）'

func fill_name_list():
	name_list.clear()
	for idx in range(names.size()):
		name_list.add_item(names[idx] + get_tag_surfix(tags_list[idx]))

func on_post_request_completed( result, response_code, headers, body ):
	if result != HTTPRequest.RESULT_SUCCESS:
		return action_menu.enable_sync()
	if response_code >= 400:
		return action_menu.enable_sync()

	action_menu.disable_sync()

func on_date_update(year, month, day):
	date_time.year = year
	date_time.month = month
	date_time.day = day
	update_title()
	fetch_data()

func update_button_state(_i):
	if name_list.get_selected_items().size() == 0:
		btn_edit.set_disabled(true)
		btn_delete.set_disabled(true)
	else:
		btn_edit.set_disabled(false)
		btn_delete.set_disabled(false)

func on_panel_hide():
	get_tree().set_auto_accept_quit(true)

class Helper:
	func pad_num(num):
		if num < 10:
			return '0' + str(num)
		else:
			return str(num)
	func date_to_str(dt):
		return str(dt.year) + '-' + pad_num(dt.month) + '-' + pad_num(dt.day)
	func get_url(dt):
		var date_str = date_to_str(dt)
		return api_origin + '?date=' + date_str + '&loc=11'
	func http_result_to_str(code):
		if code == 2:
			return '无法连接到服务器'
		elif code == 3:
			return '无法解析服务器地址'
		elif code == 4:
			return '连接中遇到读写错误'
		else:
			return '未知'
